package com.donger.sso.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.extra.spring.SpringUtil;
import com.donger.sso.system.dto.UserInfo;
import com.donger.sso.system.entity.SysUser;
import com.donger.sso.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author pmc
 * <p>
 * 用户相关工具类
 */
@Slf4j
public class AuthUtils {


    public static final Map<String, Object> CACHE_MAP = Dict.create();


    /**
     * 获取登陆用户id
     *
     * @return
     */
    public static Long getUserId() {
        return StpUtil.getLoginIdAsLong();
    }

    /**
     * 获取用户信息
     * 获取远程用户中心用户信息，
     * 然后根据用户id 进行缓存
     * 缓存信息 10分钟自动失效
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        Long userId = getUserId();
        if (CACHE_MAP.containsKey(String.valueOf(userId))) {
            return (UserInfo) CACHE_MAP.get(String.valueOf(userId));
        } else {
            SysUserService bean = SpringUtil.getBean(SysUserService.class);
            SysUser user = bean.getById(userId);
            UserInfo userInfo = new UserInfo();
            BeanUtil.copyProperties(user, userInfo);
            CACHE_MAP.put(String.valueOf(userId), userInfo);
            return userInfo;
        }
    }


}
